<template>
	<view>
		<use-navbar title="我的" bgColor="#ff6a6c"></use-navbar>
		
		<view class="padding-lr padding-tb-lg bg-base">
			<view class="dflex-a">
				<view class="dflex" @click="showStas = true">
					<image :src="userObj.member_headimg || '/static/images/user/default.png'" mode="aspectFill"
						class="border-radius-c margin-right-sm"
						style="width: 110rpx; height: 110rpx; border: 2px solid #fff;"></image>
					<view class="">
						<view class="fwb ft-white fs-30">
							{{ userObj.member_nickname || appabbr || '图腾' }}
						</view>
						<view style="opacity: .6;">
							<view v-if="userObj.slogan"><text class="fs-xxs">{{ userObj.slogan }}</text></view>
							<view v-else-if="userObj.member_city"><text class="fs-xxs">{{ userObj.member_city }}</text></view>
						</view>
					</view>
				</view>
				
				<!-- 当前是登录者自己 -->
				<view v-if="iself" 
					class="border-radius-lg fwbd bg-main ft-base padding-tb-16 padding-lr-xl"
					@click="toNote">写笔记</view>
				<!-- 未开通的情况下显示 -->
				<view v-if="isload && !(noteUser && noteUser._id)"
					class="border-radius-lg fwbd bg-main ft-base padding-tb-16 padding-lr-xl"
					@click="toNote">去开通</view>
			</view>
			<view class="margin-top-xl">
				<view class="dflex">
					<view class="tac flex1" @click="to('/sub-shopping/pages/follow')">
						<view class="ft-white fwb fs-xl">{{ noteUser._id && noteUser.notep_attention.length + '' || '--' }}</view>
						<view class="ft-main fs-xs">关注</view>
					</view>
					<view class="tac flex1" @click="to('/sub-shopping/pages/fans')">
						<view class="ft-white fwb fs-xl">{{ noteUser._id && noteUser.notep_fans.length + '' || '--' }}</view>
						<view class="ft-main fs-xs">粉丝</view>
					</view>
					<view class="tac flex1" @click="showStas = true">
						<view class="ft-white fwb fs-xl">{{ noteUser._id && (noteUser.notep_praise + noteUser.notep_by_collect) + '' || '--' }}</view>
						<view class="ft-main fs-xs">获赞与收藏</view>
					</view>
				</view>
			</view>
		</view>

		<view class="bg-base w-full" style="height: 80rpx;"></view>
		<view class="w-full bg-drak data-area">
			<!-- tab 区 -->
			<view class="dflex-c w-full bg-drak padding-lr-lg padding-top-lg padding-bottom-sm fs data-area" style="position: sticky; top: -10px; z-index: 9;"
				:style="{ 'border-radius': `${borderRadius}rpx` }">
				<view class="padding-lr dflex-c" v-for="(item, idx) in navDatas" :key="idx" 
					:class="{active: curTab === idx}" @click="curTab = idx">
					{{item.text}}
					<text class="fs-xs margin-left-xs" v-if="idx == 0">{{ noteUser._id && (noteUser.notep_note) }}</text>
					<text class="fs-xs margin-left-xs" v-else="tabDatas['u_' + idx].loaded">{{ tabDatas['u_' + idx].cnt || '' }}</text>
				</view>
			</view>
			<!-- swiper 区 -->
			<view class="goodsContent border-radius">
				<swiper skip-hidden-item-layout :duration="300" :current="curTab" style="min-height: 80vh;"
					:style="{ width: '100vw', height: swiperHeight }" @change="swiperChange">
					<swiper-item v-for="(nav, idx) in navDatas" :key="idx">
						<view :id="'u_' + idx" class="dflex padding-top-sm padding-lr dflex-s">
							<!-- 左侧 -->
							<view class="margin-right-xs wpre-50 overflow-hidden">
								<view class="dflex-b dflex-wrap-w">
									<view class="product-box pos-r" v-for="(item, pidx) in tabDatas['u_' + idx].left" :key="item._id" @click="toDetail(item)">
										<view class="bg-main margin-bottom-sm border-radius">
											<view class="pos-r" style="width: 335rpx;height: 335rpx;">
												<image lazy-load class="wh-full" :src="item.img" mode="aspectFill"></image>
												<view v-if="item.isvideo" class="iconfont iconbofang pos-a ft-base fs-xl" style="top: 10rpx; right: 10rpx;"></view>
											</view>
											<view class="padding-lr-sm margin-top-sm clamp-2">{{item.note_title}}</view>
											<view class="dflex-b padding-lr-sm margin-tb-sm">
												<!-- 可删除 -->
												<view v-if="iself" class="dflex flex1" style="width: 60%;" @click.stop="toOper(item, idx, 'left')">
													<view class="iconfont iconlajitong-01"></view>
													<view class="clamp ft-dark margin-left-xs fs-xxs">删除</view>
												</view>
												<!-- 笔记人 -->
												<view v-else class="dflex flex1" style="width: 60%;">
													<image :src="item.create_uheadimg || '/static/images/user/default.png'" class="border-radius-c headimg" style="width: 50rpx; height: 50rpx;"></image>
													<view class="ft-dark margin-left-xs fs-xxs">{{item.create_uname}}</view>
												</view>
												<!-- 点赞 -->
												<view class="dflex">
													<view class="iconfont iconaixin"></view>
													<view class="clamp ft-dark margin-left-xs fs-xxs">{{item.note_praise}}</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
							<!-- 右侧 -->
							<view class="margin-left-xs wpre-50 overflow-hidden">
								<view class="dflex-b dflex-wrap-w">
									<view class="product-box pos-r" v-for="(item, pidx) in tabDatas['u_' + idx].right" :key="item._id" @click="toDetail(item)">
										<view class="bg-main margin-bottom-sm border-radius">
											<view class="pos-r" style="width: 335rpx;height: 335rpx;">
												<image lazy-load class="wh-full" :src="item.img" mode="aspectFill"></image>
												<view v-if="item.isvideo" class="iconfont iconbofang pos-a ft-base fs-xl" style="top: 10rpx; right: 10rpx;"></view>
											</view>
											<view class="padding-lr-sm margin-top-sm clamp-2">{{item.note_title}}</view>
											<view class="dflex-b padding-lr-sm margin-tb-sm">
												<!-- 可删除 -->
												<view v-if="iself" class="dflex flex1" style="width: 60%;" @click.stop="toOper(item, idx, 'right')">
													<view class="iconfont iconlajitong-01"></view>
													<view class="clamp ft-dark margin-left-xs fs-xxs">删除</view>
												</view>
												<!-- 笔记人 -->
												<view v-else class="dflex flex1" style="width: 60%;">
													<image :src="item.create_uheadimg || '/static/images/user/default.png'" class="border-radius-c headimg" style="width: 50rpx; height: 50rpx;"></image>
													<view class="ft-dark margin-left-xs fs-xxs">{{item.create_uname}}</view>
												</view>
												<!-- 点赞 -->
												<view class="dflex">
													<view class="iconfont iconaixin"></view>
													<view class="clamp ft-dark margin-left-xs fs-xxs">{{item.note_praise}}</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							
							</view>
						</view>
						
						<!-- 空白页 -->
						<use-empty-emoji v-if="tabDatas['u_' + idx].loaded && tabDatas['u_' + idx].empty" e-style="round" e-type="note"
							tip=" " btn-tip="去写笔记" height="80vh" @to="to('/sub-shopping/pages/note')"></use-empty-emoji>
						
						<!-- 上拉加载更多 -->
						<use-loadmore v-if="tabDatas['u_' + idx].loaded && !tabDatas['u_' + idx].empty && tabDatas['u_' + idx].hasmore" :type="tabDatas['u_' + idx].loadingType"></use-loadmore>
					</swiper-item>
				</swiper>
				
			</view>
		</view>
		<!-- 加载中 -->
		<use-loading :loaded="tabDatas['u_' + curTab].loaded" mode="pos-f"></use-loading>
						
		<use-popup v-model="showStas" bgclass=" " mode="center" borderRadius="20">
			<view class="padding-lr-xl stats-area">
				<view class="dflex-s dflex-flow-c padding-left-lg">
					<view class="dflex-c">
						<view class="ft-white border-radius-c dflex-c circle" style="background: #ff6a6c;">
							<text class="iconfont iconmingxi"></text>
						</view>
						<text class="margin-lr-sm ft-dark">当前发布笔记数</text>
						<text>{{ noteUser._id && (noteUser.notep_note) + '' || '--' }}</text>
					</view>
					<view class="dflex-c margin-tb-sm">
						<view class="ft-white border-radius-c dflex-c circle" style="background: #6f96f1;">
							<text class="iconfont iconaixin"></text>
						</view>
						<text class="margin-lr-sm ft-dark">当前获得点赞数</text>
						<text>{{ noteUser._id && (noteUser.notep_praise) + '' || '--' }}</text>
					</view>
					<view class="dflex-c">
						<view class="ft-white border-radius-c dflex-c circle" style="background: #ffbc49;">
							<text class="iconfont iconshoucang-01"></text>
						</view>
						<text class="margin-lr-sm ft-dark">当前发布收藏数</text>
						<text>{{ noteUser._id && (noteUser.notep_by_collect) + '' || '--' }}</text>
					</view>
				</view>
				<view class="bg-base margin-top-xl tac w-full border-radius-lg padding-tb-sm" @click.stop="showStas = false">
					我知道了
				</view>
			</view>
		</use-popup>

		<!-- 置顶 -->
		<use-totop ref="usetop" @to="toHeader"></use-totop>
	</view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex';
	export default {
		computed: {
			...mapState(['member', 'islogin']),
			userObj() {
				if (!this.isload) return {};
				
				return (this.noteUser && this.noteUser.user) || this.member;
			},
			iself() {
				if (!this.isload) return false;
				
				return this.noteUser && this.noteUser.iself;
			},
			appabbr() {
				return this.$config.appabbr;
			}
		},
		data() {
			let tabDatas = {};
			for (let i = 0; i < 3; i++) {
				tabDatas['u_' + i] = { datas: [], left: [], right: [], page: 1, cnt: 0, top: 0, empty: false, hasmore: false, loaded: false, loadingType: 'more', ids: [], val: null };
			}
			
			return {
				uid: '',
				isload: false,
				loaded: false,
				curTab: 0,
				prevIdx: 0,
				tabDatas: tabDatas,
				navDatas: [],
				noteUser: {},
				showStas: false,
				swiperHeight: '100vh',
				reqData: {
					rows: 30
				},
				borderRadius: 80
			};
		},
		onLoad(res) {
			if (!this.islogin) return;
			
			this.uid = this.member._id;
			if (res.id) {
				this.uid = res.id;
			}
			
			this.navDatas = [{ text: '笔记' }, { text: '点赞' }, { text: '收藏' }];
			this.navDatas.forEach((item, idx) => {
				this.initCurData(idx);
			});
			
			this.initCurData();
			this.loadNoteDatas();
			
			// 点赞数据同步
			uni.$on('__shopping_likes', (res) => {
				console.log('点赞数据同步 user ', res);
				if (this.iself) {
					// 重新初始化 点赞 tab
					this.initCurData(1);
				}
			});
			
			// 收藏数据同步
			uni.$on('__shopping_collect', (res) => {
				console.log('收藏数据同步 user ', res);
				if (this.iself) {
					// 重新初始化 收藏 tab
					this.initCurData(2);
				}
			});
		},
		onUnload() {
			uni.$off(['__shopping_likes', '__shopping_collect'])
		},
		onShow(res) {
			console.log('onShow', this.islogin);
			if (!this.islogin) {
				this.$api.tologin(true);
				return;
			}
			
			// 加载用户数据
			this.loadData();
			
			if (this.curTab > 0 && this.iself) {
				// 重新加载点赞、收藏数据
				this.loadNoteDatas();
			}
		},
		onReachBottom(res) {
			console.log('onReachBottom', res);
			this.loadNoteDatas();
		},
		onPageScroll(e) {
			if (e.scrollTop <= 200) this.borderRadius = `${80 - 80 * e.scrollTop / 200}`;
			
			
			this.tabDatas['u_' + this.curTab].top = e.scrollTop;
			
			this.$refs.usetop.change(e.scrollTop);
		},
		methods: {
			loadData() {
				if (!this.islogin) return;
				
				this.$func.usemall.call('shopping/user', { id: this.uid }).then(res => {
					console.log('note-user', res);
					this.isload = true;
					if (res.code == 200) {
						this.noteUser = res.datas;
						return;
					}
				});
			},
			// 加载笔记数据
			loadNoteDatas() {
				let __curidx = this.curTab;
				console.log('this.tabDatas', this.tabDatas, __curidx);
				let curData = this.tabDatas[`u_${__curidx}`];
				if (['loading', 'nomore'].includes(curData.loadingType)) { 
					//防止重复加载
					return; 
				}
				// 当前数据加载中
				curData.loadingType = 'loading';
				
				// 用户
				this.reqData.uid = this.uid;
				this.reqData.ids = curData.ids;
				this.reqData.val = curData.val;
				this.reqData.islikes = 0;
				this.reqData.iscollect = 0;
				
				if (__curidx == 1) {
					// 点赞
					this.reqData.islikes = 1;
				}
				if (__curidx == 2) {
					// 收藏
					this.reqData.iscollect = 1;
				}
				
				this.$func.usemall.call('shopping/list', this.reqData).then(res => {
					if (!this.loaded) this.loaded = true;
					if (!curData.loaded) curData.loaded = true;
					
					console.log('shopping.list res', res, );
					if (res.code == 200) {
						let leftDatas = [];
						let rightDatas = [];
						
						const datasLength = res.datas.length;
						if (datasLength <= 0 || datasLength < this.reqData.rows) {
							// 当前数据为空或返回数据小于请求 rows，则没有更多数据
							curData.loadingType = 'nomore';
						} else {
							curData.loadingType = 'more';
							curData.page == 1 ? curData.hasmore = !0 : null;
						}
						
						res.datas.forEach((x, i) => {
							if (curData.datas.find(p => p == x._id)) return;
							
							// 当前数据的顺序
							x.__idx = curData.cnt + i;
							
							// 是否已点赞
							x.likes = x.likes || false;
							x.islikes = false;
							
							if (x.note_imgs && x.note_imgs.length > 0) {
								x.img = x.note_imgs[0].url;
							} 
							
							if (x.note_video && x.note_video.url) {
								x.img = x.note_video.url + '?x-oss-process=video/snapshot,t_5000,f_jpg,w_750,m_fast';
								x.isvideo = true;
							}
							
							i % 2 == 0 ? leftDatas.push(x) : rightDatas.push(x);
							
							if (i+1 == datasLength) {
								// 设置最后一条请求参数值
								this.setReqData(curData, x, res.datas);
							}
						});
						
						// 第一页
						if (curData.page == 1) {
							curData.cnt = 0;
							curData.left = leftDatas;
							curData.right = rightDatas;
							curData.datas = res.datas.map(x => x._id);
						} else {
							curData.left = [...curData.left, ...leftDatas];
							curData.right = [...curData.right, ...rightDatas];
							curData.datas = [...curData.datas, ...res.datas.map(x => x._id)];
						}
						
						curData.page++;
						
						// 记录总数据数
						curData.cnt = curData.left.length + curData.right.length;
						
						// 当前数据为空
						curData.empty = false;
						if (curData.cnt <= 0) {
							curData.empty = true;
						}
						
						
						this.$nextTick(() => {
							const view = uni.createSelectorQuery().in(this);
							view.select(`#u_${this.curTab}`)
								.boundingClientRect(data => {
									data.height += 40;
									curData.offset = Object.freeze(data);
									// console.log('boundingClientRect', data, curData);
									this.swiperHeight = curData.offset.height + 'px';
								})
								.exec()
						})
					}
				});
			},
			// 设置请求参数值
			setReqData(cur, data, datas) {
				cur.val = data.create_time;
				cur.ids = datas.filter(x => x.create_time == cur.val).map(x => x._id);
			},
			initCurData(idx) {
				if (typeof idx === 'undefined') idx = this.curTab;
				
				let curData = this.tabDatas['u_' + idx];
				// 清除存储的分页条件数据
				curData.val = null;
				curData.ids = [];
				curData.page = 1;
				curData.cnt = 0;
				curData.datas = [];
				curData.left = [];
				curData.right = [];
				curData.loaded = false;
				curData.hasmore = true;
				curData.loadingType = 'more';
				
				return curData;
			},
			toHeader() {
				// 回顶部
				// 重新初始化 scrollTop 值
				for (let key in this.tabDatas) {
					this.tabDatas[key].top = 0;
				}
			},
			swiperChange(e) {
				console.log('swiperChange', e);
				if (e.detail) {
					this.curTab = e.detail.current;
					const curData = this.tabDatas['u_' + this.curTab];
					const prevData = this.tabDatas['u_' + this.prevIdx];
					
					let flag = true;
					for (let key in this.tabDatas) {
						if (this.tabDatas[key] >= 200) {
							flag = false;
						}
					}
					
					if (flag) {
						// 选项卡都小于 200情况下，默认滚动到上一个位置
						curData.top = prevData.top;
					} else {
						// 其中一个大于 200情况下，当前小于 200的默认等于 200
						if (curData.top >= 0 && curData.top < 200) {
							curData.top = 200;
						} 
					}
					
					uni.pageScrollTo({
						scrollTop: curData.top,
						duration: 300
					})
					if (curData.offset && curData.offset.height) {
						this.swiperHeight = curData.offset.height + 'px';
					}
					
					this.loadNoteDatas();
					
					this.$nextTick(() => {
						const view = uni.createSelectorQuery().in(this);
						view.select(`#u_${this.curTab}`)
							.boundingClientRect(data => {
								data.height += 40;
								curData.offset = Object.freeze(data);
								// console.log('boundingClientRect', data, curData);
								this.swiperHeight = curData.offset.height + 'px';
							})
							.exec()
					})
					
					// 存储上一个 tab idx
					this.prevIdx = e.detail.current;
				}
			},
			// 统一跳转接口，拦截未登录路由
			to(url) {
				if (!this.islogin) {
					this.$api.tologin()
					return;
				}
			
				uni.navigateTo({
					url
				});
			},
			// 跳转详情页
			toDetail(res) {
				uni.setStorage({
					key: '__shopping_detail_data',
					data: res
				});
				uni.setStorage({
					key: '__shopping_detail_datas',
					data: [...this.tabDatas['u_' + this.curTab].left, ...this.tabDatas['u_' + this.curTab].right]
				});
				
				uni.navigateTo({
					url: `/sub-shopping/pages/detail?id=${res._id}`
				});
			},
			// 开通笔记|写笔记
			toNote() {
				if (this.noteUser && this.noteUser._id) {
					this.to('/sub-shopping/pages/note');
					return;
				}
				
				this.toOpen();
			},
			// 开通笔记
			toOpen() {
				if (this.isubimt) return;
				
				this.isubimt = true;
				uni.showLoading({ title: '开通中' });
				
				this.$func.usemall.call('shopping/openNote')
					.then(res => {
						this.isubimt = false;
						uni.hideLoading();
						if (res.code === 200) {
							this.$api.msg('开通成功');
							this.loadData();
							return;
						}
						
						this.$api.msg(res.msg);
					})
				return;
			},
			toOper(item, idx, pos) {
				uni.showModal({
					content: '删除',
					confirmText: '确定',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							if (this.isoper) return;
							
							let url = '';
							switch (idx){
								case 0:
									// 删除笔记
									url = 'shopping/del';
									break;
								case 1:
									// 取消点赞
									url = 'shopping/likesCancel';
									break;
								case 2:
									// 取消收藏
									url = 'shopping/collectCancel';
									break;
								default:
									this.$api.msg(`[${idx}]未配置`);
									return;
							}
							uni.showLoading({
								title: '请求中'
							});
							this.isoper = true;
							this.$func.usemall.call(url, { id: item._id }).then(res => {
								console.log('toOper', url, res);
								uni.hideLoading();
								this.isoper = false;
								if (res.code == 200) {
									// 删除当前数据
									let __idx = this.tabDatas['u_' + this.curTab][pos].findIndex(x => x._id == item._id);
									this.tabDatas['u_' + this.curTab][pos].splice(__idx, 1);
									
									if (idx == 0) {
										// 笔记-1
										this.noteUser.notep_note--;
										if (this.noteUser.notep_note < 0) this.noteUser.notep_note = 0;
									} else if (idx == 1 || idx == 2) {
										// 点赞-1
										// 收藏-1
										this.tabDatas['u_' + idx].cnt--;
										if (this.tabDatas['u_' + idx].cnt < 0) this.tabDatas['u_' + idx].cnt = 0;
										if (this.tabDatas['u_' + idx].cnt == 0) {
											this.tabDatas['u_' + idx].empty = true;
										}
									} 
									return;
								}
								
								this.$api.msg(res.msg);
							})
						}
					}
				})
			}
		},
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;
	}

	.data-area {
		border-top-left-radius: 80rpx;
		border-top-right-radius: 80rpx;
		position: relative;
		top: -80rpx;
	}

	.active {
		line-height: 1.2;
		color: #000 !important;
		font-weight: bold;
		position: relative;

		&:after {
			content: ' ';
			position: absolute;
			width: 40%;
			height: 8rpx;
			border-radius: 4rpx;
			background: #ff6a6c;
			bottom: -6rpx;
			left: 50%;
			transform: translateX(-50%);
		}
	}


	.fans-headimg {
		width: 60rpx;
		height: 60rpx;
	}

	.stats-area {
		width: 80vw;
		padding: 70rpx 80rpx 60rpx;
		
		.circle {
			width: 50rpx;
			height: 50rpx;
		}
		
		.iconfont {
			font-size: 28rpx;
		}
	}

	.goodsContent {
		width: 100%;
		display: flex;
		justify-content: center;

		.ft-dark {
			color: #585858;
		}
	}

	.goodsLeftList,
	.goodsRightList {
		width: 50%;
		overflow: hidden;
	}

	.goodsLeftList {
		margin-right: 10rpx;
	}

	.goodsRightList {
		margin-left: 10rpx;
	}
</style>
